package com.renbang.utils.drawandindex;

import java.io.File;
import java.io.IOException;
//import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class Higlight {
	private static String INDEX_DIR = "F:/简书";
	private static Analyzer analyzer = null;
	private static Directory directory = null;

	
	public static List<Word> MultiFieldQuery(String text) throws Exception{

			List<Word> list = new ArrayList<Word>();
			directory = FSDirectory.open(new File(INDEX_DIR));// 索引文件夹
			analyzer = new IKAnalyzer();
			DirectoryReader ireader = DirectoryReader.open(directory);
			IndexSearcher isearcher = new IndexSearcher(ireader);
			/**
			 * 用MultiFieldQueryParser类实现对同一关键词的跨域搜索
			 * */
			
			String[] field = { "title", "content" };
			MultiFieldQueryParser parser = new MultiFieldQueryParser(
					Version.LUCENE_40, field, analyzer);
			parser.setDefaultOperator(QueryParser.OR_OPERATOR);
			Query query = parser.parse(text);
//			
//			  QueryParser parser = new QueryParser(Version.LUCENE_40, "content", analyzer);
//            parser.setDefaultOperator(QueryParser.OR_OPERATOR);//设置默认逻辑‘或’查询
//            Query query = parser.parse(text);
			
			TopDocs topDocs = isearcher.search(query, 500);// 查找 //初步用跨域同条件筛选出来得索引。
			System.out.println("共检索出 " + topDocs.totalHits + " 条记录");
			Formatter formatter = new SimpleHTMLFormatter("<font color='red'>",
					"</font>");
			QueryScorer scorer = new QueryScorer(query);
			Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
			Highlighter highlighter = new Highlighter(formatter, scorer);
			// 设置高亮后的字符长度
			highlighter.setTextFragmenter(fragmenter);
			highlighter.setTextFragmenter(new SimpleFragmenter());
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			
			Word word;
			for (ScoreDoc score : scoreDocs) {
				Document document = isearcher.doc(score.doc);
				// String str = "ID:" + document.get("log_id") + "姓名："
				// + document.get("user_name") + "内容:";
				word = new Word();
				String id = document.get("aticleId");
				String value = document.get("content");
				String name = document.get("title");
				word.setWordId(Integer.valueOf(id));
				word.setLink("developer/jiasnhu/showArticle?aticleId="+id);
					String content = highlighter.getBestFragment(analyzer,
							"content", value);
					if(content!=null){
						word.setContent(content);
					}else{
						if(value.length()>100)
							word.setContent(value.substring(0, 100));
						else
							word.setContent(value);
					}
					//System.out.println("内容：" + word.getContent());
					String title = highlighter.getBestFragment(analyzer,
							"title", name);
					if(title!=null){
						word.setTitle(title);//标题含关键字变红
					}else{
						word.setTitle(name);//标题不含关键字
					}
					//System.out.println("标题：" + word.getTitle());
					list.add(word);
			}
			ireader.close();
			directory.close();
			return list;
		
	}
	
	
	 public static Word searchIdIndex(String filed,String value) throws Exception{
	        	List<Word> list = new ArrayList<Word>();
	            directory = FSDirectory.open(new File(INDEX_DIR));//索引文件夹
	            analyzer = new IKAnalyzer();
	            DirectoryReader ireader = DirectoryReader.open(directory);
	            IndexSearcher isearcher = new IndexSearcher(ireader);
	            QueryParser parser = new QueryParser(Version.LUCENE_40, filed, analyzer);
	            parser.setDefaultOperator(QueryParser.AND_OPERATOR);//设置默认逻辑‘或’查询
	            Query query = parser.parse(value);
	            TopDocs topDocs = isearcher.search(query, 1);
	            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
	            Word word;
	            for (ScoreDoc score : scoreDocs) {
	            	Document document = isearcher.doc(score.doc);
					word = new Word();
					String id = document.get("aticleId");
					word.setTitle(document.get("title"));
					word.setContent(document.get("content"));
					word.setWordId(Integer.valueOf(id));
					word.setLink("developer/jiasnhu/showArticle?aticleId="+id);
					list.add(word);
	            }
	            ireader.close();
				directory.close();
				return list.get(0);
	    }

	public static void main(String[] args) {
		// searchIndexHigLight("系统登录");
		try {
			MultiFieldQuery("普通人");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
